
//1.声明构造函数
function Promise(executor) {
  //4.添加属性
  this.PromiseState = 'pending'; //默认Promise实例对象状态属性
  this.PromiseResult = null; //默认Promise实例对象携带值
  const self = this; //保存Promise实例对象 resolve,reject函数内的this指向window
  this.callbacks = []; //8.执行器 executor 执行异步方法,并处理多个then方法调用
  //resolve 函数 功能实现
  function resolve(data) {
    if (self.PromiseState !== 'pending') return; //6.Promise 的状态只能修改一次
    console.log('this-resolve--', this)
    self.PromiseState = 'fulfilled'; //4.修改Promise实例对象的状态属性
    self.PromiseResult = data; //4.对Promise的实例对象进行赋值
    self.callbacks.forEach(item=>{ //8.执行器 executor 执行异步方法,并处理多个then方法调用
      item.onResolved(data);
    })
  }
  //reject 函数  功能实现
  function reject(data) {
    if (self.PromiseState !== 'pending') return; //6.Promise 的状态只能修改一次
    console.log('this-reject--', this)
    self.PromiseState = 'rejected'; //4.修改Promise实例对象的状态属性
    self.PromiseResult = data; //4.对Promise的实例对象进行赋值
    self.callbacks.forEach(item=>{ //8.执行器 executor 执行异步方法,并处理多个then方法调用
      item.onRejected(data);
    })
  }
  //3.同步调用[执行器]函数
  try {
    executor(resolve, reject)
  } catch (error) {
    //5.处理 Promise 执行器内部抛出错误 改变 Promise 状态
    reject(error)
  }
}
//2.添加then方法
Promise.prototype.then = function (onResolved, onRejected) {
  if (this.PromiseState === 'fulfilled') { //7.处理then方法的返回值
    onResolved(this.PromiseResult)
  }
  if (this.PromiseState === 'rejected') {  //7.处理then方法的返回值
    onRejected(this.PromiseResult)
  }
  if (this.PromiseState === 'pending') {  //8.执行器 executor 执行异步方法
      this.callbacks.push({
        onResolved:onResolved,
        onRejected:onRejected
      })
  }
};
